package org.example.nio_demo;

import org.junit.Test;
import sun.plugin2.message.SetChildWindowHandleMessage;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.rmi.ServerError;
import java.util.Date;

/**
 * @ClassName DemoBlockingNIO2
 * @Description
 * @Author zhangsw
 * @Date 2020/11/14 10:03
 * @Version 1.0
 */
public class DemoBlockingNIO2 {

    @Test
    public void client() throws IOException {
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\Users\\zhangsw\\Desktop\\work\\S70603-12241603.mp4"), StandardOpenOption.READ);
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while ((inChannel.read(buffer)) != -1) {
            buffer.flip();
            sChannel.write(buffer);
            buffer.clear();
        }

        //阻塞式IO需要调用 shutdownOutput 方法
        sChannel.shutdownOutput();

        //接收服务端的反馈
        int len = 0;
        while ((len = sChannel.read(buffer)) != -1) {
            buffer.flip();
            System.err.println(new String(buffer.array(), 0, len));
            buffer.clear();
        }

        inChannel.close();
        sChannel.close();
    }

    @Test
    public void server() throws IOException {
        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\Users\\zhangsw\\Desktop\\work\\server22.mp4"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ssChannel.bind(new InetSocketAddress(9898));
        SocketChannel sChannel = ssChannel.accept();
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while ((sChannel.read(buffer)) != -1) {
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
        }

        //发送消息反馈客户端
        buffer.put("服务端接收数据成功".getBytes());
        buffer.flip();
        sChannel.write(buffer);

        sChannel.close();
        outChannel.close();
        ssChannel.close();
    }

    @Test
    public void test1() {
        String dateStr = new Date().toLocaleString();
        System.err.println(dateStr);

        String s = new Date().toString();
        System.out.println(s);
    }
}

